
from dataclasses import asdict, dataclass
from functools import lru_cache
from json import loads,dumps
from pathlib import Path
from xdg import xdg_config_home

from typing_extensions import Final

ORGANISATION_NAME: Final[str]  = "spark-store-console"
PACKAGE_NAME: Final[str] = 'consoleapp'

@dataclass
class Config:
    ''''''
    theme: str = "textual-dark"
    ''''''

def config_file() -> Path:

    (config_dir := xdg_config_home() / ORGANISATION_NAME / PACKAGE_NAME).mkdir(
        parents=True, exist_ok=True
    )
    return config_dir / 'config.json'

def save_config(config: Config) -> Config:

    load_config.cache_clear()
    config_file().write_text(dumps(asdict(config), indent=4))

    return load_config()

@lru_cache(maxsize=None)
def load_config() -> Config:
    '''Load the configuration file.'''
    source_file = config_file()
    return (
        Config(**loads(source_file.read_text()))
        if source_file.exists()
        else save_config(Config())
    )

